package com.yang.mybatis.proxy;

import com.yang.mybatis.config.MybatisSqlStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapperProxy<T> implements InvocationHandler {
    private Map<String, MybatisSqlStatement> sqlSessionMap = new HashMap<>();

    private Class<T> mapperInterface;

    public MapperProxy(Class<T> mapperInterface, List<MybatisSqlStatement> mybatisSqlStatementList) {
        this.mapperInterface = mapperInterface;
        for (MybatisSqlStatement mybatisSqlStatement : mybatisSqlStatementList) {
            String mapperName = mybatisSqlStatement.getNamespace();
            String id = mybatisSqlStatement.getId();
            String key = mapperName + "." + id;
            sqlSessionMap.put(key, mybatisSqlStatement);
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        String key = this.mapperInterface.getName() + "." + method.getName();
        return "你的被代理了!" + sqlSessionMap.get(key).getSql();
    }
}
